package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.properties.MailProperties;
import com.cskaoyan.user.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author karlfu
 * @since 2022/06/18 10:00
 */

@Slf4j
@Service
public class IRegisterServiceImpl implements IRegisterService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailProperties mailProperties;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();

        // 判空
        registerRequest.requestCheck();

        // 验证用户名或者邮箱是否重复（前端注册不需要手机，故不验证）
        validUserRepeat(registerRequest);

        //1. 向用户表插入注册的记录
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());

        // 对密码进行md5加密处理
        String encodedUserPwd = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes(StandardCharsets.UTF_8));
        member.setPassword(encodedUserPwd);

        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);

        // 2. 向用户验证表中插入一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();;
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes(StandardCharsets.UTF_8));
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");

        try {
            Boolean insertOK = insertMemberAndVerify(member, userVerify);
            if (!insertOK) {
                throw new Exception();
            }
        } catch (Exception e) {
            e.printStackTrace();
            userRegisterResponse.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            userRegisterResponse.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
            return userRegisterResponse;
        }

        // 3. 发送用户激活邮件
        sendMailMessage(uuid,registerRequest);

        // 若发送邮件成功 则返回SUCCESS
        log.info("用户注册成功，注册参数request:{}", JSON.toJSONString(registerRequest));
        userRegisterResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        userRegisterResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return userRegisterResponse;
    }

    /**
     * 发送邮件
     * @param uuid
     * @param registerRequest
     */
    private void sendMailMessage(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 邮件主题
        mailMessage.setSubject(mailProperties.getSubject());
        // 邮件发送方
        mailMessage.setFrom(mailProperties.getFrom());
        // 邮件接收方
        mailMessage.setTo(registerRequest.getEmail());
        // 邮件内容
        // http://localhost:${server.port}/user/verify?username=%s&uuid=%s
        // 拼接username,uuid
        mailMessage.setText(mailProperties.getText()
                .replaceFirst("%s", registerRequest.getUserName())
                .replace("%s", uuid));
        // 发送邮件
        mailSender.send(mailMessage);
    }

    // 两个表的插入操作要封装为事务
    @Transactional
    Boolean insertMemberAndVerify(Member member, UserVerify userVerify) {
        // 1. 向用户表插入注册的记录
        int insertM = memberMapper.insert(member);

        // 2. 向用户验证表中插入一条记录
        int insertV = userVerifyMapper.insert(userVerify);

        return insertM == 1 && insertV == 1;
    }

    private void validUserRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());
        example.createCriteria().orEqualTo("email",registerRequest.getEmail());

        List<Member> members = memberMapper.selectByExample(example);
        // 用户名或者邮箱已存在
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(SysRetCodeConstants.DATA_REPEATED.getCode(),SysRetCodeConstants.DATA_REPEATED.getMessage());
        }
    }
}
